import Vue from 'vue'
import VueRouter from 'vue-router'



Vue.use(VueRouter)

const routes = [
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login.vue')
  },
  {
    path:'/',
    name:'layout',
    component:()=> import('../views/layout.vue'),
       // 嵌套路由
       children:[
        {
          path:'/users',
          name:'users',
          meta:{
            title:'用户管理'
          },
          component:()=>import('../views/user.vue')
        },
        {
          path:'/rights',
          name:'rights',
          meta:{
            title:'权限列表'
          },
          component:()=>import('../views/Rights.vue')
        },
        {
          path:'/roles',
          name:'roless',
          meta:{
            title:'角色列表'
          },
          component:()=>import('../views/Roles.vue')
        },
      ]
  }
]

const router = new VueRouter({
  routes
})
//后置守卫
router.afterEach((to,from) =>{
  console.log(to.meta.title);
  Vue.prototype.$bus.$emit('getTitle',to.meta.title)
  localStorage.setItem('title',to.meta.title)
  document.title= to.meta.title
}),

//路由导航守卫
router.beforeEach((to,from,next)=>{
  if(to.path=='/login') return next()
  //获取缓存中的token
  let token = localStorage.getItem('admin_token')
  if(!token)return next ('/login')
  next()
  // to:要访问的路径
  //from:来路
  //next()放行
})


export default router
